<template>
  <div>
    <el-form ref="resList" :disabled="formDis" :model="resList" :rules="rules" label-width="120px" class="demo-ruleForm" style="margin-top: 20px;">
      <el-form-item label="会员等级名称" prop="levelName">
        <el-col :span="8" >
          <el-input v-model="resList.levelName" maxlength="100" placeholder="请输入会员等级名称" />
        </el-col>
      </el-form-item>
      <el-form-item label="会员等级" prop="level">
        <el-col :span="8" >
          <el-input v-model="resList.level" type="number" placeholder="数字越大等级越高，1 - 99" />
        </el-col>
      </el-form-item>
      <el-form-item label="有效期" prop="expiryDate">
        <el-col :span="8">
          <el-form-item prop="expiryDate">
            <el-date-picker
              v-model="resList.expiryDate"
              type="datetime"
              placeholder="请选择有效期" />
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="" prop="integral">
        <el-col :span="8">
          <el-form-item prop="integral">
            <el-checkbox v-model="resList.integral">可积分</el-checkbox>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="充值金额" prop="price">
        <el-col :span="6" >
          <el-input v-model="resList.price" type="number" placeholder="请填写充值金额" />
        </el-col>
        &nbsp;&nbsp;元
      </el-form-item>
      <el-form-item label="" prop="recharge">
        <el-col :span="8">
          <el-form-item prop="recharge">
            <el-checkbox v-model="resList.recharge">可充值</el-checkbox>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="是否启用" prop="startUsing">
        <el-select v-model="resList.startUsing" placeholder="请选择是否启用">
          <el-option :value="0" label="是" />
          <el-option :value="1" label="否" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button v-preventReClick v-if="isEdit" type="primary" @click="submitForm('resList')">确定</el-button>
        <el-button v-preventReClick v-else type="primary" @click="submitForm('resList')">新增</el-button>
        <el-button @click="resetForm('resList')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import config from '@/utils/config';
import { checkPhone, checkIdCard, checkEmail } from '@/utils/regUtil';
import { checkNotEmail, checkNum, checkStudentNum } from '@/utils/validateUtil';
import { getTeacherList } from '@/api/teacher'
import { addCours, editCours } from '@/api/course'
import Tinymce from '@/components/Tinymce'
import { GetQiniuToken } from '@/utils/qiniuUpload.js'
import { Message } from 'element-ui'
import mixin from '@/mixin'

const validatePass = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入新密码'));
  } else if (value.toString().length < 6 || value.toString().length > 100) {
    callback(new Error('密码长度为6 - 100个字符'))
  } else {
    callback();
  }
};

const validatephone = (rule, value, callback) => {
  if (!checkPhone(value)) {
    callback(new Error())
  }
  callback()
};
const validateIdCard = (rule, value, callback) => {
  if (!checkIdCard(value)) {
    callback(new Error())
  }
  callback()
};
const validateMail = (rule, value, callback) => {
  if (!checkNotEmail(value)) {
    callback(new Error())
  }
  callback()
};
// const validateNum = (rule, value, callback) => {
//   if (!checkNum(value)) {
//     callback(new Error())
//   }
//   callback()
// };
const validateStudentNum = (rule, value, callback) => {
  if (!checkStudentNum(value)) {
    callback(new Error())
  }
  callback()
};

const validateStudentNumber = (rule, value, callback) => {
  if (value.length > 5) {
    callback(new Error())
  }
  callback()
};

const validateZero = (rule, value, callback) => {
  if (!checkNum(value)) {
    callback(new Error())
  }
  callback()
};

export default {
  components: { Tinymce },
  mixins: [mixin],
  data() {
    return {
      teacher: [],
      resList: {
        levelName: '', // 会员等级名称
        level: '', // 等级
        expiryDate: '', // 有效期
        integral: false, // 可积分
        price: '', // 充值金额
        isPrice: false, // 可充值
        startUsing: '' // 是否启用
      },
      rules: {
        levelName: [
          { required: true, message: '会员等级名称', trigger: 'blur' },
          { max: 100, message: '输入字符不得超过100个', trigger: 'blur' }
        ],
        level: [
          { required: true, message: '请输入等级', trigger: 'blur' }
        ],
        expiryDate: [
          { required: true, message: '请选择有效期', trigger: 'blur' }
          // { validator: validateNum, message: '请输入数字', trigger: 'blur' },
        //   { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '数值需大于0', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请填写充值金额', trigger: 'blur' },
          // { validator: validateNum, message: '请输入数字', trigger: 'blur' },
          { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '数值需大于0', trigger: 'blur' }
        ],
        startUsing: [
          { required: true, message: '请输选择是否启用', trigger: 'blur' }
          // { validator: validateNum, message: '请输入数字', trigger: 'blur' },
        //   { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '数值需大于0', trigger: 'blur' }
        ]

        // signupCommission: [
        //   { required: true, message: '请输入分享提成', trigger: 'blur' },
        //   // { validator: validateNum, message: '请输入数字', trigger: 'blur' },
        //   { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '数值需大于0', trigger: 'blur' }
        // ]
        // stuNumber: [
        //   { required: true, message: '请输入学生人数', trigger: 'blur' },
        //   { validator: validateStudentNum, message: '请输入整数', trigger: 'blur' },
        //   { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '活动人数需大于0', trigger: 'blur' },
        //   { validator: validateStudentNumber, message: '长度为1-5位数字', trigger: 'blur' }
        // ],
        // startDate: [
        //   { required: true, message: '请选择开始日期', trigger: 'change' }
        // ],
        // endDate: [
        //   { required: true, message: '请选择结束日期', trigger: 'change' }
        // ],
        // address: [
        //   { required: true, message: '请输入地址', trigger: 'blur' },
        //   { min: 12, max: 40, message: '长度12-40个字符', trigger: 'blur' }
        // ],
        // tid: [
        //   { required: true, message: '请选择讲师', trigger: 'change' }
        // ],
        // introduction: [
        //   { required: true, message: '课程介绍不能为空', trigger: 'blur' }
        // ],
        // cPlan: [
        //   { required: true, message: '课程安排不能为空', trigger: 'blur' },
        //   { max: 1000, message: '长度不能超过1000个字符', trigger: 'blur' }
        // ],
        // costDesc: [
        //   { required: true, message: '费用说明不能为空', trigger: 'blur' },
        //   { max: 1000, message: '长度不能超过1000个字符', trigger: 'blur' }
        // ],
        // precautions: [
        //   { required: true, message: '注意事项不能为空', trigger: 'blur' },
        //   { max: 1000, message: '长度不能超过1000个字符', trigger: 'blur' }
        // ]
      },
      fileList: [],
      actionUrl: config.BaseUrl + '/image/upload',
      uploadData: {
        key: '',
        token: ''
      },
      formDis: false,
      tinymceDis: false,
      isEdit: false,
      selectShow: false,
      // 对应<请选择讲师下拉菜单>查询教师信息列表时，把status为1的教师获取出来
      listQuery: {
        pageNum: 0,
        pageSize: 1000,
        status: 1
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      isDisabled: false
    }
  },
  computed: {
    ruleForm: function() {
      return this.$store.getters.ruleForm
    }
  },
  watch: {
    ruleForm: {
      handler: function(nowVal, oldVal) {
        this.$store.dispatch('AddlistenForm', this.ruleForm).then(() => {
        }).catch((err) => {
          Message.error(err.err)
        })
      },
      deep: true
    }
  },
  created() {
  },
  mounted() {
    const _self = this;
    console.log('this.$route.query:', JSON.stringify(this.$route.query))
    if (this.$route.query && JSON.stringify(this.$route.query) !== '{}') {
      this.isEdit = this.$route.query.hasOwnProperty('isEdit') ? _self.$route.query.isEdit : false;
      this.formDis = Boolean(this.$route.query.isLook)
      this.tinymceDis = Boolean(this.$route.query.isLook)
      const a = this.$route.query
      if (a.hasOwnProperty('isLook')) {
        this.dataToHtml(a)
        this.selectShow = true
        delete a.isLook;
      }
      if (a.hasOwnProperty('isEdit')) {
        this.dataToHtml(a)
        // this.getTeacherList()
        delete a.isEdit;
      }
      this.$store.dispatch('AddlistenForm', this.$route.query).then(() => {
      }).catch((err) => {
        Message.error(err.err)
      })
    } else { // 新增
      // this.getTeacherList()
      this.$store.dispatch('resetFunc').then(() => {
      }).catch((err) => {
        Message.error(err.err)
      })
    }
    this.uploadData.token = GetQiniuToken().uploadToken
  },
  methods: {
    request(data) {
      data.startDate = new Date(data.startDate).getTime();
      data.endDate = new Date(data.endDate).getTime();
      this.dataToCode(data)
      this.isEdit ? editCours(data).then(response => {
        if (Number(response.code) === 200) {
          Message.success('编辑成功')
          this.$router.go(-1);
        } else {
          Message.error(response.message + '-' + response.data)
        }
      }) : addCours(data).then(response => {
        if (Number(response.code) === 200) {
          Message.success('新增成功')
          this.$router.go(-1);
        } else {
          Message.error(response.message + '-' + response.data)
        }
      });
    },
    dataToHtml(query) {
      query.cPlan = this.changeToHtml(query.cPlan)
      query.costDesc = this.changeToHtml(query.costDesc)
      query.precautions = this.changeToHtml(query.precautions)
    },
    dataToCode(data) {
      data.cPlan = this.changeToCode(data.cPlan)
      data.costDesc = this.changeToCode(data.costDesc)
      data.precautions = this.changeToCode(data.precautions)
    },
    changeToCode(str) {
      return str.replace(/\r\n|\r|\n/g, '<br/>')
    },
    changeToHtml(str) {
      return str.replace(/<br\s*\/?>/g, '\n')
    },
    getTeacherList() {
      getTeacherList(this.listQuery).then(response => {
        this.teacher = response.data.list
        console.log(this.teacher.length)
        this.selectShow = true
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.ruleForm)
          if (new Date(this.ruleForm.startDate).getTime() >= new Date(this.ruleForm.endDate).getTime()) {
            Message.error('活动开始时间必须小于结束时间')
            return false
          }
          if (new Date(this.ruleForm.startDate).getTime() <= new Date().getTime()) {
            Message.error('活动开始时间必须大于当前时间')
            return false
          }
          if (new Date(this.ruleForm.endDate).getTime() <= new Date().getTime()) {
            Message.error('活动结束时间必须大于当前时间')
            return false
          }
          this.request(this.ruleForm)
        } else {
          this.validateError()
          return false;
        }
      });
    },
    resetForm() {
      this.resList.levelName = '' // 会员等级名称
      this.resList.level = '' // 等级
      this.resList.expiryDate = '' // 有效期
      this.resList.integral = false // 可积分
      this.resList.price = '' // 充值金额
      this.resList.isPrice = false // 可充值
      this.resList.startUsing = '' // 是否启用
    //   this.$store.dispatch('resetFunc').then(() => {
    //   }).catch((err) => {
    //     Message.error(err.err)
    //   })
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove(file, fileList) {
      if (file && file.status === 'success') {
        return this.$confirm(`确定移除 ${file.name}？`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {})
      }
    },
    beforeAvatarUpload(file) {
      const isPNG = file.type === 'image/png'
      const isJPEG = file.type === 'image/jpeg'
      const isJPG = file.type === 'image/jpg'
      const isGIF = file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isPNG && !isJPEG && !isJPG && !isGIF) {
        this.$message.error('上传头像图片只能是 jpg、png、jpeg、gif 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      this.uploadData.key = `upload_pic_${new Date().getTime()}_${file.name}`
    },
    change(type, file, fileList) {
      if (Number(fileList.response.code) === 200) {
        let obj;
        switch (type) {
          case 'coverImg':
            obj = {
              coverImg: config.ImgUrl + fileList.response.data
            };
            break;
          case 'posterImg':
            obj = {
              posterImg: config.ImgUrl + fileList.response.data
            };
            break;
        }
        this.$store.dispatch('addListenerCoverImg', obj).then(() => {
          Message.success('图片上传成功')
        }).catch((err) => {
          Message.error(err.err)
        })
      }
    }
  }
}
</script>

<style>
  .tip {
    color: red;
  }
  .tin_box {
    border: 1px solid #ddd;
    padding: 0 10px 0 10px;
    color:#666;
  }
  .line{
    text-align: center;
  }
</style>
